package org.apache.log4j;

import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;

import log.tiny.TinyLog;
import log.util.CommUtil;
import log.util.Constant;

public class Logger {

	private static final TinyLog log = TinyLog.getInstance();
	private static final ConcurrentMap<String, Logger> loggerMap = new ConcurrentHashMap<String, Logger>();
	private String className;

	public Logger(String name) {
		this.className = name;
	}

	public static Logger getLogger(Class<?> clazz) {
		return getLogger(clazz.getName());
	}

	public static Logger getLogger(String name) {
		Logger log4jLogger = loggerMap.get(name);
		if (log4jLogger == null) {
			Logger newInstance = new Logger(name);
			Logger oldInstance = loggerMap.putIfAbsent(name, newInstance);
			return oldInstance == null ? newInstance : oldInstance;
		} else {
			return log4jLogger;
		}
	}

	public void log(String callerFQCN, Priority p, Object msg, Throwable throwable) {
		if ((p.level == Constant.TRACE || p.level == Constant.DEBUG || p.level == Constant.INFO)
				&& log.denyClassName(className))
			return;
		if (p.level == Constant.TRACE || p.level == Constant.DEBUG || p.level == Constant.INFO)
			log.writeLog(p.logFileName, p.level, className);
		StringBuilder infos = new StringBuilder();
		if (msg != null) {
			infos.append(msg);
		}
		if (throwable != null) {
			infos.append(TinyLog.endStr).append(CommUtil.getExpStack(throwable));
		}
		log.writeLog(p.logFileName, p.level, infos);
	}

	public boolean isDebugEnabled() {
		return log.isDebugEnabled();
	}

	public boolean isInfoEnabled() {
		return log.isInfoEnabled();
	}

	public boolean isEnabledFor(Priority p) {
		return Constant.LOG_LEVEL <= p.level;
	}

}